package client.airportForm;
import client.ClientSender;
import static client.airportForm.AddPortDialog.airport;
import exception.AirportNotFoundException;
import exception.InvalidArgumentsException;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.concurrent.TimeoutException;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.*;
/**
 *
 * @author GeneraL
 */
public class AirportShowPanel extends javax.swing.JPanel {

    /**
     * Creates new form AirportShowPanel
     */
    private ArrayList<Integer> portId;
    private ArrayList<String> portType;
    private ArrayList<String> portName;
    private ArrayList<String> portLocation;

    public AirportShowPanel() {
        initComponents();
       
    }
    public void reloadPorts(){
     try{
     ClientSender sender=new ClientSender();
     ArrayList<Airport> airports=sender.sendPort("portlist");
     sender.close();
     ArrayList<Integer> id=new ArrayList<Integer>();  
     ArrayList<String> portType=new ArrayList<String>();
     ArrayList<String> portName=new ArrayList<String>();
     ArrayList<String> portLocation=new ArrayList<String>();
     for(int i=0;i<airports.size();i++){
         id.add(airports.get(i).getId());
         portType.add(airports.get(i).getClass().getSimpleName());
         portLocation.add(airports.get(i).getLocation());
         portName.add(airports.get(i).getName());
     }
     this.setData(id,portType, portName, portLocation);
        }catch (UnknownHostException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
            System.exit(0);
        }
        catch (IOException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
            System.exit(0);
        }
        catch (TimeoutException | AirportNotFoundException | InvalidArgumentsException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
        }
    }

    /**
     * установка выводимых параметров аэропортов
     * @param portType
     * @param portName
     * @param portLocation 
     */
    public void setData(ArrayList<Integer> portId,ArrayList<String> portType,ArrayList<String> portName,ArrayList<String> portLocation){
       this.portId=portId;
        this.portType=portType;
       this.portName=portName;
       this.portLocation=portLocation;
       String[] portUniqueName=new String[portType.size()];
       javax.swing.DefaultListModel model=new javax.swing.DefaultListModel<>();
       for(int i=0;i<portName.size();i++){
           portUniqueName[i]=new String("№"+portId.get(i)+": "+portName.get(i));
           model.addElement(portUniqueName[i]);
       }
      
        this.portList.setModel(model);
        this.delButton.setEnabled(false);
        this.setButton.setEnabled(false);
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane2 = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        addButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        portList = new javax.swing.JList();
        jPanel2 = new javax.swing.JPanel();
        delButton = new javax.swing.JButton();
        airportInfoPanel = new client.airportForm.AirportInfoPanel();
        setButton = new javax.swing.JButton();

        addButton.setText("Добавить аэропорт");
        addButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addButtonActionPerformed(evt);
            }
        });

        portList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        portList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                portListMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(portList);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(addButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(addButton))
        );

        jSplitPane2.setLeftComponent(jPanel1);

        delButton.setText("Удалить аэропорт");
        delButton.setEnabled(false);
        delButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                delButtonActionPerformed(evt);
            }
        });

        setButton.setText("Сохранить изменения");
        setButton.setEnabled(false);
        setButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                setButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(airportInfoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 393, Short.MAX_VALUE)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(delButton, javax.swing.GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
                    .addComponent(setButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(197, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addComponent(airportInfoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(setButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(delButton)
                .addContainerGap(125, Short.MAX_VALUE))
        );

        jSplitPane2.setRightComponent(jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jSplitPane2)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSplitPane2))
        );
    }// </editor-fold>//GEN-END:initComponents
/**
 * добавление азропорта
 * @param evt 
 */
    private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
        // TODO add your handling code here:
        //addport
                AddPortDialog dialog = new AddPortDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                    }
                });
            Airport airport=dialog.showDialog();
        this.reloadPorts();//заглушка! перезагрузка всей базы данных аэропортов

    }//GEN-LAST:event_addButtonActionPerformed
/**
 * удаление аэропорта
 * @param evt 
 */
    private void delButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delButtonActionPerformed
        // TODO add your handling code here:
        //dellport
       // System.err.println("delport "+this.portId.get(this.portList.getSelectedIndex()));
        try{
        ClientSender send=new ClientSender();
        ArrayList<Airport> airports=send.sendPort("delport "+this.portId.get(this.portList.getSelectedIndex()));
        send.close();
        this.reloadPorts();//заглушка! перезагрузка всей базы данных аэропортов
        if(airports.size()>0)airport=airports.get(0);
        }catch (UnknownHostException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
        }
        catch (IOException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
        }
        catch (TimeoutException | AirportNotFoundException | InvalidArgumentsException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
        }  
    }//GEN-LAST:event_delButtonActionPerformed
/**
 * запрошена детализация аэропорта
 * @param evt 
 */
    private void portListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_portListMouseClicked
        // TODO add your handling code here:
        int i=this.portList.getSelectedIndex();
        this.airportInfoPanel.setData(portType.get(i), portName.get(i), portLocation.get(i));
        this.delButton.setEnabled(true);
        this.setButton.setEnabled(true);


    }//GEN-LAST:event_portListMouseClicked
/**
 * переименование полей аэропорта
 * @param evt 
 */
    private void setButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_setButtonActionPerformed
        // TODO add your handling code here:
         /*System.err.println("setport "+
                 this.portId.get(this.portList.getSelectedIndex())+" "+
                 airportInfoPanel.getPortName()+" "+airportInfoPanel.getPortLocation());*/
               try{
        ClientSender send=new ClientSender();
        ArrayList<Airport> airports=send.sendPort("setport "+
                 this.portId.get(this.portList.getSelectedIndex())+" "+
                 airportInfoPanel.getPortName()+" "+airportInfoPanel.getPortLocation());
        send.close();
        this.reloadPorts();//заглушка! перезагрузка всей базы данных аэропортов
        if(airports.size()>0)airport=airports.get(0);
        }catch (UnknownHostException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
        }
        catch (IOException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
        }
        catch (TimeoutException | AirportNotFoundException | InvalidArgumentsException  e){
            JOptionPane.showMessageDialog(new JFrame(), e.getMessage(), "Exeption",JOptionPane.ERROR_MESSAGE);
            System.err.println(e.getMessage());
        } 
         
         
    }//GEN-LAST:event_setButtonActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addButton;
    private client.airportForm.AirportInfoPanel airportInfoPanel;
    private javax.swing.JButton delButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane2;
    private javax.swing.JList portList;
    private javax.swing.JButton setButton;
    // End of variables declaration//GEN-END:variables
}
